import datetime
from django.core.paginator import Paginator
from django.db.models import Q
from django.views import View
from django.http import JsonResponse
import json

from ihome.utils import constants

from ihome.utils.image_storage import storage

from order.models import Order
from users.models import User
from .models import Area, House


# 城区列表接口
class AreasView(View):
    def get(self, request):

        try:
            # 获取所有城区对象
            areas = Area.objects.filter().all()

        except Exception as e:
            return JsonResponse({'errno':404, 'errmsg': '没有找到相应的信息'}, status=404)

        # 定义一个城区对象列表
        areas_list = []
        for area in areas:
            areas_list.append({
                'aid': area.id,
                'aname': area.name
            })

        # 构建响应
        return JsonResponse({
            'errno': 0,
            'errmsg': '获取成功',
            'data': areas_list
        })

# 首页房屋推荐
class Houses_index_html(View):

    def get(self, request):

        # 定义一个空列表,用于存放房屋对象
        data = []
        houses = House.objects.all()[0:3]
        for house in houses:
            data.append({
                'house_id': house.id,
                'img_url': constants.QINIU_DOMIN_PREFIX_laoshi + house.index_image_url,
                'title': house.title
            })

        # 构建响应
        return JsonResponse({
            'errno': '0',
            'errmsg': 'OK',
            'data': data
        })

# 发布房源和搜索房源
class HousesView(View):

    def post(self, request):
        # 判断用户是否登陆
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({
                "errno": 400,
                "errmsg": "请登录"
            })

        data = json.loads(request.body.decode())
        title = data.get("title")
        price = data.get("price")
        area_id = data.get("area_id")
        address = data.get("address")
        room_count = data.get("room_count")
        acreage = data.get("acreage")
        unit = data.get("unit")
        capacity = data.get("capacity")
        beds = data.get("beds")
        deposit = data.get("deposit")
        min_days = data.get("min_days")
        max_days = data.get("max_days")
        facility = data.get("facility")

        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days, facility]):
            return JsonResponse({
                "errno": 400,
                "errmsg": "缺少参数"
            })

        try:
            # house = House.objects.create(**data)
            house = House.objects.create(
                user=User.objects.get(id=user.id),
                area=Area.objects.get(id=area_id),
                title=title,
                price=price,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days
            )


        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "发布房源失败"
            })

        return JsonResponse({
            "errno": 0,
            "errmsg": "发布成功",
            "data": {"house_id": house.id}
        })

    # 房屋搜索
    def get(self, request):
        # 1.提取参数
        aid = request.GET.get('aid')  # 区域id
        sd = request.GET.get('sd')  # 入住时间
        ed = request.GET.get('ed')  # 离开时间
        sk = request.GET.get('sk')  # 排序方式
        p = request.GET.get('p', 1)  # 页数

        # 2.校验参数
        if sd > ed:
            return JsonResponse({'errno': '400', 'errmsg': '参数错误'}, status=400)

        order_str = ""
        if sk == 'booking':
            order_str = "order_count"
        elif sk == 'new':
            order_str = "-update_time"
        elif sk == 'price-inc':
            order_str = "price"
        elif sk == 'price-des':
            order_str = "-price"
        else:
            return JsonResponse({'errno': '400', 'errmsg': '请求错误'}, status=400)

        # 如果没有筛选地区和日期,则搜索出所有的房源
        if not (aid and sd and ed):
            houses_objs = House.objects.all().order_by(order_str)

        # 如果没有筛选地区
        if not aid:
            houses_objs = House.objects.all().order_by(order_str)

        # 如果没有筛选日期
        elif not sd and not ed:
            houses_objs = House.objects.filter(area_id=aid).order_by(order_str)

        # 数据处#理
        else:
            # 计算用户入住天数sum_date
            count_dates = datetime.datetime.strptime(ed, '%Y-%m-%d') - datetime.datetime.strptime(sd, '%Y-%m-%d')
            sum_date = count_dates.days

            houses_objs = House.objects.filter(
                Q(area_id=aid,
                  min_days__lte=sum_date,
                  max_days__gt=sum_date) | Q(
                    area_id=aid,
                    min_days__lte=sum_date,
                    max_days=0
                )
            ).order_by(order_str)

        # 获取所有订单
        order = Order.objects.all()
        # 将订单关联的房屋id放到列表里
        order_list = []
        for li in order:
            order_list.append(li.house_id)

        houses_list = []
        for house in houses_objs:

            # 如果房子的id不在订单所关联的房子id --> 说明房子没有被预订
            if house.id not in order_list:
                area = Area.objects.get(id=house.area_id)
                user = User.objects.get(id=house.user_id)

                houses_list.append({
                    "address": house.address,
                    "area_name": area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": constants.QINIU_DOMIN_PREFIX + house.index_image_url,
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": constants.QINIU_DOMIN_PREFIX + user.avatar.url
                })

        # 4.构建响应
        return JsonResponse({
            'errno': '0',
            'errmsg': '请求成功',
            'data': {
                'houses': houses_list,
                # 'total_page': paginator.num_pages  # 总页数
                'total_page': p  # 总页数
            }
        })


# 房屋详情页
class House_msg_view(View):
    def get(self, request, house_id):
        print(house_id)
        data = {}
        # 先获取房源表数据
        house = House.objects.get(pk=house_id)

        # 房源详细信息
        house_dict = house.to_full_dict()

        data["house"] = {
            **house_dict,
            'user_id': house.user.id,
        }
        print(data['house']['user_id'])
        return JsonResponse({
            'data': data,
            'errno': '0',
            'errmsg': 'OK'
        })

# 上传房源图片
class Hose_sourse_View(View):
    def post(self, request, house_id):
        print(house_id)
        # 1:提取参数
        image_file = request.FILES.get('house_image', None)
        # 2:校验参数
        if image_file is None:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        # 3:数据处理---读取数据(二进制)，上传到七牛云，将返回的地址，保存到数据库
        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片上传失败"
            })

        try:
            # house = HouseImage.objects.create(house=house_id, url=file_name)
            # print(house_id)
            house = House.objects.get(pk=house_id)
            house.index_image_url = file_name
            house.save()

        except Exception as e:
            # print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })

        url = constants.QINIU_DOMIN_PREFIX + file_name
        # 4：构建响应
        return JsonResponse({
            "data": {
                "url": url
            },
            "errno": "0",
            "errmsg": "图片上传成功",
        })
